<template>
  <div class="mod-user">
    <el-row :gutter="20">
      <el-col :xs="9" :sm="6" :md="5" :lg="4" :xl="4">
        <div class="head-container">
          <el-input
            v-model="deptName"
            clearable
            size="small"
            placeholder="输入部门名称搜索"
            prefix-icon="el-icon-search"
            class="filter-item"
            @input="getDeptDatas"
            style="width:60%"
          />
           <el-button @click="resetForm()">重置</el-button>
        </div>
        <el-tree
          :data="deptDatas"
          :props="defaultProps"
          :loading="deptListLoading"
          @node-click="handleNodeClick"
        />
      </el-col>
      <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
        <el-form
          :inline="true"
          :model="dataForm"
          @keyup.enter.native="getDataList()"
        >
          <el-form-item>
            <el-input
              v-model="dataForm.userName"
              placeholder="用户名"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="" prop="startTime">
            <el-date-picker
              v-model="dataForm.startTime"
              type="date"
              placeholder="选择开始日期"
              :picker-options="startTime"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd 00:00:00"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="" prop="endTime">
            <el-date-picker
              v-model="dataForm.endTime"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd 23:59:59"
              placeholder="选择结束日期"
              :picker-options="endTime"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button @click="getDataList()" type="primary">查询</el-button>
            <el-button
              v-if="isAuth('sys:user:save')"
              type="primary"
              @click="addOrUpdateHandle()"
              >新增</el-button
            >
            <el-button
              v-if="isAuth('sys:user:delete')"
              type="danger"
              @click="deleteHandle()"
              :disabled="dataListSelections.length <= 0"
              >批量删除</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          :data="dataList"
          border
          v-loading="dataListLoading"
          @selection-change="selectionChangeHandle"
          style="width: 100%;"
        >
          <el-table-column
            type="selection"
            header-align="center"
            align="center"
            width="50"
          >
          </el-table-column>
          <el-table-column
            prop="username"
            header-align="center"
            align="center"
            label="用户名"
          >
          </el-table-column>
          <el-table-column
            prop="nickName"
            header-align="center"
            align="center"
            label="昵称"
          >
          </el-table-column>
          <el-table-column
            prop="gender"
            header-align="center"
            align="center"
            label="性别"
          >
          </el-table-column>
           <el-table-column
            prop="mobile"
            header-align="center"
            align="center"
            label="手机号"
          >
          </el-table-column>
          <el-table-column
            prop="email"
            header-align="center"
            align="center"
            label="邮箱"
          >
          </el-table-column>
           <el-table-column
            prop="deptName"
            header-align="center"
            align="center"
            label="部门"
          >
          </el-table-column>
          <el-table-column
            prop="status"
            header-align="center"
            align="center"
            label="启用状态"
          >
            <template slot-scope="scope">
              <el-switch
                :disabled="userId === scope.row.userId"
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="changeStatus(scope.row, scope.row.status)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            header-align="center"
            align="center"
            width="180"
            label="创建时间"
          >
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="150"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button
                v-if="isAuth('sys:user:update')"
                type="text"
                size="small"
                @click="addOrUpdateHandle(scope.row.userId,scope.row.deptName)"
                >修改</el-button
              >
              <el-button
                v-if="isAuth('sys:user:delete')"
                type="text"
                size="small"
                @click="deleteHandle(scope.row.userId)"
                :disabled="scope.row.userId === userId"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
      </el-col>
    </el-row>

    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      :userId="userId"
      :addDeptId="addDeptId"
      :addDeptName="addDeptName"
      :deptName="userDeptName"
      @refreshDataList="getDataList"
    ></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from "./user-add-or-update";
export default {
  data() {
    return {
      //日期的限制
      startTime: {
        // 禁用的日期
        disabledDate: time => {
          // 如果已经已知结束日期，就把结束日期之后的日期禁用
          if (this.dataForm.endTime) {
            return time.getTime() > new Date(this.dataForm.endTime).getTime();
          } else {
            // 否则 就把当前日期之后的日期禁用掉
            // return time.getTime() > Date.now()
          }
        }
      },
      endTime: {
        disabledDate: time => {
          // 如果已知开始日期，就把开始日期之前的日期禁用掉
          if (this.dataForm.startTime) {
            return time.getTime() < new Date(this.dataForm.startTime).getTime();
          }
        }
      },
      addDeptId:0,
      addDeptName:"",
      userDeptName:"",//部门名称
      deptName: "", //搜索框的部门名称
      updateStatus: "",
      dataForm: {
        userName: "",
        startTime: null,
        endTime: null
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      deptListLoading: false,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      defaultProps: {
        children: "children",
        label: "name"
      },
      deptDatas: [],
      deptId:""
    };
  },
  computed: {
    userId: {
      get() {
        return this.$store.state.user.id;
      }
    }
  },
  components: {
    AddOrUpdate
  },
  activated() {
    this.getDataList();
    this.getDeptDatas();
  },
  mounted() {},
  created() {},
  methods: {
    resetForm(){
      this.deptId = "";
      this.getDataList();
    },
    //切换部门
    handleNodeClick(data){
      debugger
      this.deptId = data.deptId;
      this.addDeptName = data.name;
      this.addDeptId = data.deptId;
      this.getDataList();

    },
    getDeptDatas() {
      this.deptListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/sys/dept/list"),
        method: "get",
        params: this.$http.adornParams({
          key: this.deptName
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.deptDatas = data.list;
        } else {
          this.deptDatas = [];
        }
        this.deptListLoading = false;
      });
    },
    //改变状态
    changeStatus(data, val) {
      if (val === 1) {
        this.updateStatus = "启用";
      } else {
        this.updateStatus = "停用";
      }
      this.$confirm(
        '此操作将 "' +
          this.updateStatus +
          '" ' +
          data.username +
          ", 是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/sys/user/status"),
            method: "post",
            data: this.$http.adornData({
              status: val,
              userId: data.userId
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success"
              });
              this.getDataList();
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {
          data.status = !data.status;
        });
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/sys/user/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          startTime: this.dataForm.startTime,
          endTime: this.dataForm.endTime,
          username: this.dataForm.userName,
          deptId:this.deptId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(id,deptName) {
      debugger
      this.userDeptName = deptName;
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    // 删除
    deleteHandle(id) {
      var userIds = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.userId;
          });
      this.$confirm(
        `确定对[id=${userIds.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/sys/user/delete"),
            method: "post",
            data: this.$http.adornData(userIds, false)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    }
  }
};
</script>
